/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package proxy;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Observable;

/**
 *
 * @author root
 */
public class Servidor_IRC extends Observable implements Runnable, ISocketPeer {

    private ServerSocket socketEscuta;
    private Socket socket;
    private BufferedWriter out;
    private BufferedReader in;
    private boolean run;
    private int portaEscuta = 6667;
    private EscritorSocket escritor;

    public Servidor_IRC() {
        escritor = new EscritorSocket(this);
    }

    public Servidor_IRC(int portaEscuta) {
        this.portaEscuta = portaEscuta;
        escritor = new EscritorSocket(this);

    }

    public void stop() {
        this.run = false;
        try {
            in.close();
            out.close();
            socket.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void escreverLinha(String linha) {
        escritor.escreverLinha(linha);
    }

    public void run() {
        try {
            socketEscuta = new ServerSocket(portaEscuta);
            socket = socketEscuta.accept();
            if (socket.isConnected()) {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

                Thread t = new Thread(escritor);
                t.start();
                setChanged();
                notifyObservers(Boolean.TRUE);

                this.run = true;
                while (run) {
                    String leitura = in.readLine();
                    setChanged();
                    notifyObservers(leitura);
                }
            }

            setChanged();
            notifyObservers(Boolean.FALSE);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public BufferedWriter getBuffWriter() {
        return this.out;
    }

    public BufferedReader getBuffReader() {
        return this.in;
    }

    public Socket getSocket() {
        return this.socket;
    }

    public boolean isConectado() {
        return socket.isConnected();
    }
}
